package org.fujay.commons.langchain4j.server;

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import lombok.RequiredArgsConstructor;
import org.fujay.commons.langchain4j.param.EmbedParam;
import org.fujay.commons.langchain4j.rag.processor.document.EnhancedDocumentProcessor;
import org.fujay.commons.langchain4j.rag.processor.result.DocumentProcessResult;
import org.opensearch.client.opensearch.OpenSearchClient;
import org.springframework.stereotype.Service;

/**
 * @author slm
 * @description
 */
@Service
@RequiredArgsConstructor
public class DocumentService {

    private final EmbeddingStore<TextSegment> embeddingStore;
    private final OpenSearchClient openSearchClient;

    /**
     * @author sunliming
     * @description 加载->解析->向量化 单个文档
     */
    public DocumentProcessResult indexDoc(EmbedParam embedParam) {

        /*初始化文档处理器*/
        EnhancedDocumentProcessor enhancedDocumentProcessor = EnhancedDocumentProcessor.create(
                embedParam.getEmbeddingModel(),
                embeddingStore,
                embedParam.getUserId(),
                embedParam.getIndexName(),
                openSearchClient);
        /*文档解析*/
        Document document = enhancedDocumentProcessor.loadDocument(embedParam.getFilePath(), embedParam.getStorageStrategy());
        /*向量化*/
        return enhancedDocumentProcessor.process(document);
    }

    /**
    * @author sunliming
    * @description 文档删除
    */
    public void deleteDoc(EmbedParam embedParam) {

        /*初始化文档处理器*/
        EnhancedDocumentProcessor enhancedDocumentProcessor = EnhancedDocumentProcessor.create(
                embedParam.getEmbeddingModel(),
                embeddingStore,
                embedParam.getUserId(),
                embedParam.getIndexName(),
                openSearchClient);

        enhancedDocumentProcessor.removeDocuments(embedParam.getDocumentIds(),embedParam.getIndex());

    }
}
